
<template>
  <div :class="closeLabel === '关闭' ? 'onebill-box' : 'onebill-box box-height'">
    <div :class="closeLabel === '关闭' ? 'onebill-content content-width' : 'onebill-content'">
      <details-head v-model="status"
                    :title="`合单详情`"
                    :multiple="true"
                    :custom-list="buttonList"
                    :close-label="closeLabel"
                    @change="submit" />
      <div style="padding: 20px">
        <simple-list :info="details"
                     :base="true"
                     :icon-name="iconName"
                     :content="content"
                     :config-data="oneBillArr" />
      </div>
      <layer title="子单详情">
        <order-list :table-data="tableData"
                    :current-data="currentData"
                    :amount="amount"
                    :col-width="157"
                    :table-footer="true"
                    :selection-flag="false"
                    :operation-flag="false"
                    :combine-id="combineId" />
        <el-pagination class="pagination"
                       :current-page="page"
                       :page-size="pageSize"
                       :total="total"
                       :page-sizes="[10, 20, 50, 100]"
                       layout="total, sizes, prev, pager, next, jumper"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange">
        </el-pagination>
      </layer>
      <reject :id="combineId"
              :label="'reason'"
              :api="apiUrl"
              :title="isDispatch ? '撤销调度' : '拒绝原因'"
              :visible.sync="visible"
              id-name="combineId"
              @back="handelClose" />
      <layer v-show="isTrack"
             title="跟踪信息">
        <Information :value="track" />
      </layer>
    </div>
  </div>
</template>

<script>
import DetailsHead from "@components/detailsHead/Header.vue";
import SimpleList from "@components/orderDetail/SimpleList.vue";
import OrderList from "./components/OrderList.vue";
import Layer from "@/components/detailsLayer/Layer";
import Reject from "@/views/quote/transport/components/Reject.vue";
import { onebill, track } from "@/api/index";
import { oneBillArr } from "@components/orderDetail/orderData";
import completeData from "@/libs/conversion.js";
import Information from "@/components/track/Information.vue";

export default {
  name: "OneBillDetails",
  components: {
    DetailsHead,
    SimpleList,
    OrderList,
    Layer,
    Reject,
    Information
  },
  data () {
    return {
      api: onebill,
      page: 1,
      pageSize: 10,
      total: 0,
      details: {},
      tableData: [],
      currentData: [], //当前数据
      saveList: [],
      searchList: [],
      oneBillArr,
      orderId: null,
      amount: {
        totalQuantity: 0,
        calculateWeight: 0,
        calculateVolume: 0
      },
      status: null,
      track: [], // 跟踪信息
      isTrack: false, // 跟踪信息标题显示
      visible: false,
    };
  },
  computed: {
    combineId () {
      return this.$route.query?.combineId;
    },
    combineStatus () {
      return this.details?.status;
    },
    isDispatch () {
      // 合单管理-已调度
      return [20, 30].includes(this.combineStatus) && this.details?.waybills[0]?.waybillType === 20
    },
    buttonList () {
      if (this.isClose) {
        return [
          { label: "同意", status: "1" },
          { label: "拒绝", status: "2" }
        ];
      } else if (!this.all && this.isDispatch) {
        return [
          { label: "撤销调度", status: "3" },
          { label: "打印", status: "0" },
        ];
      } else if (this.combineStatus === 20 && !this.all && !this.isDispatch) {
        return [
          { label: "接收", status: "4" },
          { label: "拒绝", status: "5" }
        ];
      } else if (this.all || this.customerReceived) {
        return [{ label: "打印", status: "0" }]
      }
      return []
    },
    all () {
      // 新窗口打开
      const { name } = this.$route
      return name === 'oneBillDetailWindow';
    },
    customerReceived () {
      // 发货方运单-已接收合单
      return this.combineStatus === 30 && this.details?.waybills[0]?.waybillType === 10
    },
    closeLabel () {
      const { name } = this.$route
      return name === 'oneBillDetailWindow' ? '关闭' : '返回'
    },
    isClose () {
      // 关单合单
      const { name } = this.$route
      return name === 'oneBillCloseDetails'
    },
    apiUrl () {
      return this.isDispatch ? this.api.cancelDispatch : (this.isClose ? this.api.rejectedClose : this.api.rejected)
    },
    close () {
      return [10, 20, 50, 60];
    },
    content () {
      const { carrier } = this.details
      if (carrier?.carrierType === 0) {
        return '线下'
      }
      if (carrier?.carrierType === 1 && carrier?.carrierExtraType === 0) {
        return '线上'
      }
      return ''
    },
    iconName () {
      const { carrier } = this.details
      if (carrier?.carrierType === 0) {
        return 'xianxia'
      }
      if (carrier?.carrierType === 1 && carrier?.carrierExtraType === 0) {
        return 'xianshang'
      }
      return ''
    }
  },
  created () {
    this.getCombineDetail();
    this.trackInformation();
  },
  beforeDestroy () {
    clearInterval(this.timer);
  },
  methods: {
    async getCombineDetail () {
      let { code, data, message } = await onebill.getCombineDetail(
        this.combineId
      );
      if (code === 0) {
        this.details = data;
        this.details.createBy = data.createBy?.name;
        if (data.carrier) {
          this.details.carrierContactMobile = data.carrier.carrierContactMobile;
          this.details.carrierName = data.carrier.carrierName;
        }
        this.tableData = completeData.redirect(data.waybills);
        this.total = data.waybills.length;
        this.currentData = JSON.parse(JSON.stringify(this.tableData)).splice(
          0,
          this.pageSize
        );
        this.amount = {
          totalQuantity: data.totalQuantity,
          calculateWeight: Number(data.calculateWeight.toFixed(2)),
          calculateVolume: Number(data.calculateVolume.toFixed(2)),
          totalVolume: Number(data.totalVolume.toFixed(2)),
        };
      } else {
        this.$message.error(message);
      }
    },
    // 打印
    handlePrint () {
      const printerName = "CombinePrint";
      const { href } = this.$router.resolve({
        name: printerName,
        query: {
          combineId: this.combineId
        }
      });
      window.open(href, "_blank");
    },
    // 触发事件
    submit (val) {
      if (val === '0') {
        this.handlePrint();
        return
      }
      let invalidWaybill = [];    // 有关单待办的子单编号
      let financePay = [];    // 产生财务状态的子单编号 3 已结账 > 2 已对账 > 1 已加入对账单
      let financeReconciled = [];
      let financeJoin = [];
      // 预付款 > 到付款 > 代收款
      let financePrepayFee = []; // 预付款 3已收已付 > 1已收 > 2已付; 
      let financeArrivePayFee = []; // 到付款 
      let financeCollectionFee = []; // 代收款

      this.tableData.map(item => {
        if (this.close.includes(item.closeStatus)) {
          invalidWaybill.push(item.contractNo);
        }
        if (item?.finance?.financeFlag === 3) {
          financePay.push(item.contractNo);
        }
        if (item?.finance?.financeFlag === 2) {
          financeReconciled.push(item.contractNo);
        }
        if (item?.finance?.financeFlag === 1) {
          financeJoin.push(item.contractNo);
        }
        if (item?.finance?.prepayFeeFlag) {
          financePrepayFee.push(item.contractNo);
        }
        if (item?.finance?.arrivePayFeeFlag) {
          financeArrivePayFee.push(item.contractNo);
        }
        if (item?.finance?.collectionFeeFlag) {
          financeCollectionFee.push(item.contractNo);
        }
      })

      if (val === "1") {
        let flag = this.handleTips(financePrepayFee, financeArrivePayFee, financeCollectionFee, financePay, financeReconciled, financeJoin);
        if (!flag) {
          this.$confirm(`确认关单?`, "提示", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.agreeClose();
          });
        }
      } else if (val === "4") {
        this.$confirm(`确认接收?`, "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.recall();
        });
      } else if (val === '3') {
        let flag = this.handleTips(financePrepayFee, financeArrivePayFee, financeCollectionFee, financePay, financeReconciled, financeJoin);
        if (!flag) {
          // if (invalidWaybill.length) {
          //   return this.$message({ type: 'warning', message: `运单(合同号${invalidWaybill.toString()})有关单待办需要处理，不能操作` });
          // }
          this.visible = true;
        }
        return;
      } else {
        this.visible = true;
        return;
      }
    },
    handleTips (financePrepayFee, financeArrivePayFee, financeCollectionFee, financePay, financeReconciled, financeJoin) {
      let flag = false;
      // 收付款前置
      if (financePrepayFee.length) {
        flag = true;
        return this.$message({ type: 'warning', message: `运单(合同号${financePrepayFee.toString()})预付款已在收付款，不能操作` });
      } else if (financeArrivePayFee.length) {
        flag = true;
        return this.$message({ type: 'warning', message: `运单(合同号${financeArrivePayFee.toString()})货到付款已在收付款，不能操作` });
      } else if (financeCollectionFee.length) {
        flag = true;
        return this.$message({ type: 'warning', message: `运单(合同号${financeCollectionFee.toString()})代收货款已在收付款，不能操作` });
      }
      // 已结账、已对账、已加入对账单前置
      if (financePay.length) {
        flag = true;
        return this.$message({ type: 'warning', message: `运单(合同号${financePay.toString()})已结账，不能操作` });
      } else if (financeReconciled.length) {
        flag = true;
        return this.$message({ type: 'warning', message: `运单(合同号${financeReconciled.toString()})已对账，不能操作` });
      } else if (financeJoin.length) {
        flag = true;
        return this.$message({ type: 'warning', message: `运单(合同号${financeJoin.toString()})已加入对账单，不能操作` });
      }

      return flag
    },
    // 同意
    async agreeClose () {
      await onebill.agreeClose({ combineId: this.combineId });
      this.$message.success("操作成功！")
      this.handelClose()
    },
    // 接收
    async recall () {
      await onebill.recall({ combineId: this.combineId });
      this.$message.success("操作成功！")
      this.handelClose()
    },
    // 分页数量改变
    handleSizeChange (value) {
      let arr = JSON.parse(JSON.stringify(this.tableData)).splice(0, value);
      this.currentData = [...arr];
      this.page = 1;
      this.pageSize = value;
    },
    // 当前页数改变
    handleCurrentChange (value) {
      let arr = JSON.parse(JSON.stringify(this.tableData)).splice(
        (value - 1) * this.pageSize,
        value * this.pageSize
      );
      this.currentData = [...arr];
      this.page = value;
    },
    // 关闭
    handelClose () {
      this.timer = setTimeout(() => {
        this.$router.back();
        // window.close();
      }, 1000);
    },
    // 跟踪信息
    async trackInformation () {
      let type = 'combine'
      let { code, data } = await track.information(this.combineId, type);
      if (code === 0 && data.length) {
        data.map(item => {
          item.timestamp = item.message.slice(0, item.message.indexOf('，'))
          item.date = item.message.slice(item.message.indexOf('，') + 1, item.message.lastIndexOf('】') + 1)
          if (item.message.indexOf('】') == -1) {
            item.content = item.message.slice(item.message.indexOf('，') + 1)
          } else {
            item.content = item.message.slice(item.message.lastIndexOf('】') + 1)
          }
        })
        this.track = data
        this.isTrack = true
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.onebill-box {
  width: 100%;
  height: calc(100vh);
  overflow-x: hidden;
  overflow-y: scroll;
}
.box-height {
  height: calc(100vh - 80px) !important;
}
.onebill-box::-webkit-scrollbar {
  // display: none;
}
.onebill-content {
  margin: 0 auto;
  background: var(--prev-bg-white);
  min-height: 100vh;
}
.content-width {
  width: 1200px;
}
.pad20 {
  padding: 0 20px;
}

.detail_card {
  width: 1050px;
  min-width: 500px;
  margin: 0px auto;
  padding: 0 0 80px;
  overflow: hidden;
  > .el-card__body {
    padding: 0;
  }
  .des-wrap {
    margin: 20px 0;
  }
  .child_card {
    margin-bottom: 15px;
    > .el-card__body {
      padding: 0;
    }
  }
  .detail_btn {
    width: 25%;
    float: left;
  }
  .detail_checkbtn {
    width: 39%;
  }
  .tips {
    display: inline-block;
    width: 150px;
    text-align: center;
    margin: 0 43%;
    color: var(--prev-border-color-yellow);
    font-size: 13px;
  }
}

.pagination {
  display: flex;
  justify-content: flex-end;
  height: 50px;
}
</style>
